package org.zju.moviemotion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.zju.moviemotion.coverflow.CoverFlow;
import org.zju.moviemotion.coverflow.ReflectingImageAdapter;
import org.zju.moviemotion.coverflow.ResourceImageAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/****
 * The Class CoverFlowTestingActivity.
 */
public class MovieActivity extends Activity implements OnClickListener {

	// private WebView webView;
	private TextView textView;
	private ImageButton forward;
	private ImageButton back;
	// String[] introductions;
	List<String> listStr = new ArrayList<String>();
	private final static float TARGET_HEAP_UTILIZATION = 0.75f;

	private ImageView img_info;
	private RelativeLayout layout_top;
	private TextView tv_hot;
	private TextView tv_letter;
	private TextView tv_love;

	private ImageView img_heart;
	private int currentItem = 0;
	private boolean isCollected = false;
	private int[] resourcePositions;
	CoverFlow reflectingCoverFlow;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		// VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.movie);

		// introductions = getResources().getStringArray(
		// R.array.movie_introductions);

		InputStream inputStream = getResources().openRawResource(R.raw.content);
		this.getString(inputStream);
		// int size=list.size();
		// introductions = (String[])list.toArray(new String[size]);
		// webView = (WebView) findViewById(this.getResources().getIdentifier(
		// "statusText", "id", "org.zju.moviemotion"));
		textView = (TextView) findViewById(this.getResources().getIdentifier(
				"statusText", "id", "org.zju.moviemotion"));
		forward = (ImageButton) findViewById(R.id.forward);
		forward.setOnClickListener(this);
		back = (ImageButton) findViewById(R.id.back);
		back.setOnClickListener(this);

		initDatas();
		reflectingCoverFlow = (CoverFlow) findViewById(R.id.coverflow);// (this
		// .getResources().getIdentifier("coverflow", "id",
		// "org.zju.moviemotion"));
		setupCoverFlow(reflectingCoverFlow, false);

		layout_top = (RelativeLayout) findViewById(R.id.layout_top);
		img_info = (ImageView) findViewById(R.id.img_info);
		img_info.setClickable(true);
		img_info.setOnClickListener(this);
		tv_hot = (TextView) findViewById(R.id.tv_hot);
		tv_hot.setClickable(true);
		tv_hot.setOnClickListener(this);
		tv_letter = (TextView) findViewById(R.id.tv_letter);
		tv_letter.setClickable(true);
		tv_letter.setOnClickListener(this);
		tv_love = (TextView) findViewById(R.id.tv_love);
		tv_love.setClickable(true);
		tv_love.setOnClickListener(this);
		img_heart = (ImageView) findViewById(R.id.img_heart);
		img_heart.setClickable(true);
		img_heart.setOnClickListener(this);
	}

	// 初始化坐标位置，0-98
	private void initDatas() {
		resourcePositions = new int[99];
		for (int i = 0; i < 99; i++) {
			resourcePositions[i] = i;
		}
		// resourcePositions=Common.HotMovies;
	}

	private void loadHotMovies() {
		resourcePositions = Common.HotMovies;
		coverImageAdapter.setDatas(resourcePositions);
		reflectingCoverFlow.setAdapter(coverImageAdapter);
		coverImageAdapter.notifyDataSetChanged();
		reflectingCoverFlow.setSelection(0, true);
	}

	private void loadLetterMovies(char letter) {
		List<Integer> listTmp = new ArrayList<Integer>();
		int size = listStr.size();
		for (int i = 0; i < size; i++) {
			if (listStr.get(i).trim().toUpperCase().charAt(0) == letter) {
				listTmp.add(i);
			}
		}
		size = listTmp.size();
		resourcePositions = new int[size];
		for (int i = 0; i < size; i++) {
			resourcePositions[i] = listTmp.get(i);
		}
		coverImageAdapter.setDatas(resourcePositions);
		reflectingCoverFlow.setAdapter(coverImageAdapter);
		coverImageAdapter.notifyDataSetChanged();
		reflectingCoverFlow.setSelection(0, true);
	}
	private void loadLoveMovies() {
		String[] arrayLove=SettingsUtils.getLove(getApplicationContext()).split(",");
		List<Integer> listTmp = new ArrayList<Integer>();
		int size = arrayLove.length;
		for (int i = 0; i < size; i++) {
			try{
				int m=Integer.parseInt(arrayLove[i]);
				listTmp.add(m);
			}catch(Exception e){
				
			}
		}
		size = listTmp.size();
		resourcePositions = new int[size];
		for (int i = 0; i < size; i++) {
			resourcePositions[i] = listTmp.get(i);
		}
		coverImageAdapter.setDatas(resourcePositions);
		reflectingCoverFlow.setAdapter(coverImageAdapter);
		coverImageAdapter.notifyDataSetChanged();
		reflectingCoverFlow.setSelection(0, true);
	}
	ResourceImageAdapter coverImageAdapter;

	/**
	 * Setup cover flow.
	 * 
	 * @param mCoverFlow
	 *            the m cover flow
	 * @param reflect
	 *            the reflect
	 */
	private void setupCoverFlow(final CoverFlow mCoverFlow,
			final boolean reflect) {
		if (reflect) {
			// coverImageAdapter = new ReflectingImageAdapter(
			// new ResourceImageAdapter(getApplicationContext(),
			// resourcePositions));
		} else {
			coverImageAdapter = new ResourceImageAdapter(
					getApplicationContext(), resourcePositions);
		}

		mCoverFlow.setAdapter(coverImageAdapter);
		setupListeners(mCoverFlow);
		mCoverFlow.setSelection(0, true);
	}

	/**
	 * Sets the up listeners.
	 * 
	 * @param mCoverFlow
	 *            the new up listeners
	 */
	private void setupListeners(final CoverFlow mCoverFlow) {
		mCoverFlow.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(final AdapterView<?> parent,
					final View view, final int position, final long id) {
				// if (position < introductions.length) {
				// textView.setText(introductions[position]);
				// webView.loadData(introductions[position], "text/html",
				// "utf-8");
				// 打开本包内asset目录下的index.html文件

				// webView.loadUrl(" file:///android_asset/e1.html ");
				// }
				// Log.d("tag","listStr.size="+listStr.size()+";position="+position);
				Log.d("tag", String.valueOf(id));
				currentItem = position;
				if (currentItem < listStr.size()) {
					textView.setText(listStr
							.get(resourcePositions[currentItem]));
				}
				renewHeart();
			}

		});
		mCoverFlow.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(final AdapterView<?> parent,
					final View view, final int position, final long id) {
				// if (position < introductions.length) {
				// textView.setText(Html.fromHtml(introductions[position],
				// null, null));
				// textView.setText(introductions[position]);
				// webView.loadData(introductions[position], "text/html",
				// "utf-8");
				// webView.loadUrl(" file:///android_asset/e1.html ");
				// }
				// Log.d("tag","listStr.size="+listStr.size()+";position="+position);
				Log.d("tag", String.valueOf(id));
				currentItem = position;
				if (currentItem < listStr.size()) {
					textView.setText(listStr
							.get(resourcePositions[currentItem]));
				}
				renewHeart();
			}

			@Override
			public void onNothingSelected(final AdapterView<?> parent) {
				// textView.setText("Nothing clicked!");
			}
		});
	}

	private void renewHeart() {
		String loveCollection = SettingsUtils.getLove(getApplicationContext());
		List<String> listLove = new ArrayList(Arrays.asList(loveCollection
				.split(",")));
		if (listLove.contains(String.valueOf(resourcePositions[currentItem]))) {
			img_heart.setImageResource(R.drawable.love_on);
			isCollected = true;
			return;
		}
		isCollected = false;
		img_heart.setImageResource(R.drawable.love_off);
	}

	@Override
	public void onClick(View v) {
		if (v == forward) {
			startActivity(new Intent(getBaseContext(),
					NumberPickerActivity.class));
		} else if (v == back) {
			finish();
		} else if (v == img_info) {
			img_info.setVisibility(8);
			layout_top.setVisibility(0);
			Animation anim = AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_top_in);
			layout_top.startAnimation(anim);
		} else if (v == tv_hot) {
			tv_hot.setCompoundDrawablesWithIntrinsicBounds(R.drawable.select,
					0, 0, 0);
			tv_hot.setTextColor(getResources().getColor(
					R.color.movie_menu_purple));
			tv_letter.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.unselect, 0, 0, 0);
			tv_letter.setTextColor(getResources().getColor(
					android.R.color.white));
			tv_love.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.unselect, 0, 0, 0);
			tv_love.setTextColor(getResources().getColor(android.R.color.white));
			loadHotMovies();
		} else if (v == tv_letter) {
			tv_letter.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.select, 0, 0, 0);
			tv_letter.setTextColor(getResources().getColor(
					R.color.movie_menu_purple));
			tv_hot.setCompoundDrawablesWithIntrinsicBounds(R.drawable.unselect,
					0, 0, 0);
			tv_hot.setTextColor(getResources().getColor(android.R.color.white));
			tv_love.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.unselect, 0, 0, 0);
			tv_love.setTextColor(getResources().getColor(android.R.color.white));
			loadLetterMovies('A');
		} else if (v == tv_love) {
			tv_love.setCompoundDrawablesWithIntrinsicBounds(R.drawable.select,
					0, 0, 0);
			tv_love.setTextColor(getResources().getColor(
					R.color.movie_menu_purple));
			tv_letter.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.unselect, 0, 0, 0);
			tv_letter.setTextColor(getResources().getColor(
					android.R.color.white));
			tv_hot.setCompoundDrawablesWithIntrinsicBounds(R.drawable.unselect,
					0, 0, 0);
			tv_hot.setTextColor(getResources().getColor(android.R.color.white));
			loadLoveMovies();
		} else if (v == img_heart) {
			if (isCollected) {
				isCollected = false;
				img_heart.setImageResource(R.drawable.love_off);
				String loveCollection = SettingsUtils
						.getLove(getApplicationContext());
				List<String> listLove = new ArrayList(
						Arrays.asList(loveCollection.split(",")));
				listLove.remove(String.valueOf(resourcePositions[currentItem]));
				SettingsUtils.setLove(getApplicationContext(),
						listToString(listLove));
			} else {
				isCollected = true;
				img_heart.setImageResource(R.drawable.love_on);
				String loveCollection = SettingsUtils
						.getLove(getApplicationContext());
				List<String> listLove = new ArrayList(
						Arrays.asList(loveCollection.split(",")));
				listLove.add(String.valueOf(resourcePositions[currentItem]));
				SettingsUtils.setLove(getApplicationContext(),
						listToString(listLove));
			}
		}
	}

	public static String listToString(List list) {
		StringBuilder sb = new StringBuilder();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (i < list.size() - 1) {
					sb.append(list.get(i) + ",");
				} else {
					sb.append(list.get(i));
				}
			}
		}
		return sb.toString();
	}

	public String getString(InputStream inputStream) {
		InputStreamReader inputStreamReader = null;
		try {
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		BufferedReader reader = new BufferedReader(inputStreamReader);
		StringBuffer sb = new StringBuffer("");
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				// if(line.isEmpty()){
				// continue;
				// }
				if (line.length() > 5) {
					if (Character.isDigit(line.trim().charAt(0))
							&& !Character.isDigit(line.trim().charAt(3))) {
						line = line.substring(line.indexOf(".") + 1); // line.trim().replaceAll("",

						if (!sb.toString().isEmpty()) {
							listStr.add(sb.toString());
							sb.delete(0, sb.length());// 清空
						}
					}
				}
				sb.append(line);
				sb.append("\n");
			}
			listStr.add(sb.toString());
			sb.delete(0, sb.length());// 清空
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
